class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            no: '',
            id: 0,
            counts: [],
            start: 1,
            pagesize: 15,
            keyword: "",
            type: 0,
            state: 'ON',
            typehtml: [],
            statehtml: [],
            merchantName:'',
            chosefile:!1,

        };
    }

    formatlist(list) {
        var listitem = [], wulist = [];
        if (list.length > 0) {
            list.forEach((x, i) => {
                listitem.push(
                    <tr key={i}>
                        <td className="tconter" style={{ width: '50px', cursor: "pointer" }} >{x.batchNo}</td>
                        <td style={{ width: '120px' }}>{formatDate(new Date(x.createTime))}</td>
                        <td className="tconter">{getstausstr(x.status)}</td>
                        <td className="tconter">{parseFloat(Number(x.totalAmt)/100.0) }元</td>
                        <td className="tconter">{x.totalCount}</td>
                        <td className="tconter" style={{ fontSize: '9pt', cursor: "pointer" }}>{x.localFilepath}</td>
                        <td>
                            <div className="czbuttom">
                                {/* <span className="hovertxt" >请下载后保存至本地路径</span> */}
                                <p id='btn_download' onClick={this.download.bind(this, x.filePath)}>下载</p>
                                <p onClick={this.submit.bind(this, x.id)}>提交</p>
                                <p onClick={this.getdetail.bind(this, x)}>查询</p>
                            </div>
                        </td>
                    </tr>
                )
            });
        } else {
            wulist.push(
                <p className="wulist">暂无数据 !</p>
            )
        }
        this.setState({ listitem, list, originallist: list, wulist })
    }

    getdetail(x,e){
        gzgetDetail(x.id,15,1,res=>{
            // res = JSON.parse(res)
            console.log(res,'getdetail--resres');
                if(res.data.return_code!='0'){
                    
                    showAlert($('.alertarea'), res.data.returnMsg, 'alsucc', 'warning')
                   // alert(res.data.returnMsg)
                }else{
                  //  console.log();
                  if(res.data.datalist){
                      if(res.data.datalist.length>0){
                        localStorage.setItem('dlist', JSON.stringify( {list:res.data.datalist,x} ))
                        window.location.href='./detail.html'
                      }else{
                          alert('暂无数据')
                      }
                  }else{
                    alert('暂无数据')
                  }
                   

                }
        })

    }



    // 编辑
    todetail(e) {
        window.location.href = "./addgood.html?id=" + e;

        // var { list } = this.state;
        // list.forEach(x => {
        //     if (x.id == e) {
        //         this.setState({ id: e, username: x.username, password: '' })
        //     }
        // });
    }
    changestate(i, e) {
        let that = this
        that.setState({ showloading: 'ON' })
        Goodssetstate(i, res => {
            if (res.issuccess == 1) {
                this.freshlist()
                alert("设置成功")
            } else {
                that.setState({ showloading: '' })
                alert(res.msg)
            }
        })
    }
    changestate1(id, e) {
        let that = this
        that.setState({ showloading: 'ON' })
        Goodssetindex(id, res => {
            if (res.issuccess == 1) {
                this.freshlist()
                alert("设置成功")
            } else {
                that.setState({ showloading: '' })
                alert(res.msg)
            }
        })
    }
    // 排序
    toorder(id) {
        let orders = prompt("请输入1-999的正整数，数字越大，排序越前")
        if (orders == "" || orders == null) {
            return;
        }
        if (isNaN(orders) || orders < 1 || orders > 999) {
            return;
        }
        orders = Math.floor(orders);
        setGoodsorders({ id, orders }, res => {
            if (res.issuccess == 1) {
                alert("设置成功");
                // this.flist(res.list);
                this.freshlist();
            }
        });
    }
    // 删除
    // del(e) {
    //     let that = this
    //     antd.Modal.confirm({
    //         title: '提示',
    //         icon: "",
    //         content: '确定删除吗?',
    //         okText: '确定',
    //         cancelText: '取消',
    //         onOk() {
    //             that.setState({ showloading: 'ON' })
    //             delGoods(e, res => {
    //                 if (res.issuccess == 1) {
    //                     alert("删除成功")
    //                     that.freshlist()
    //                 } else {
    //                     that.setState({ showloading: '' })
    //                     alert(res.msg)

    //                 }
    //             })
    //         },
    //         onCancel() {
    //             //   console.log('Cancel');
    //         },

            
    //     });
    // }

    download(e){
        console.log(e,'eee');
        window.location.href=API_HEAD+e
    //     gzdownload(e,res=>{
          
    //         console.log(res,'resres');
    //         let blob = new Blob([res])        //创建blob方法
    //         let fileName = 'excel.xls'             //下载名称
    //         if ('download' in document.createElement('a')) { // 不是IE浏览器
    //   　 // 简单的理解一下就是将一个file或Blob类型的对象转为UTF-16的字符串，并保存在当前操作的document
    //           let url = window.URL.createObjectURL(blob)
    //           let link = document.createElement('a')            //创建a标签
    //           link.style.display = 'none'           //隐藏a标r签
    //           link.href = url                                    //指定下载url
    //           link.setAttribute('download', fileName)            //指定下载文件名称
    //           document.body.appendChild(link)        
    //           link.click()                                           //触发下载事件
    //           document.body.removeChild(link)         // 下载完成移除元素
    //           window.URL.revokeObjectURL(url) r       // 释放掉blob对象
    //         } else { // IE 10+
    //           window.navigator.msSaveBlob(blob, fileName)
    //         }

    //     })

    }

    submit(e){
        console.log(e,'eee');

        gzsubmit(e,res=>{
        const div = document.createElement('div')
let content ='<form target="_blank"'+ res.replace('<form','');

div.innerHTML = content

console.log(content,'content');
 
document.body.appendChild(div)
//let form = document.forms[1];
//form.setAttribute('target','_blank').submit()
 document.forms[1].submit()
        })
    }

    
    changefile(e){
        let that = this;
       // this.setState({chosefile:!0})
       // console.log(e,'eee');
       var form = document.getElementById('uploadthis'), 
       formData = new FormData(form); 
     $.ajax({ 
      url: `${API_HEAD}payroll/upload`, 
      type:"post", 
      data:formData, 
      processData:false, 
      contentType:false, 
      success:function(res){ 
       if(res){ 
       // alert("上传成功！");
        console.log(res,'resres');
        let resdata = JSON.parse(res).data;
        if(resdata){
            let {totalAmt,totalCount,oldPath}=resdata
            that.setState({totalAmt,totalCount,oldPath,zje:parseFloat(Number(totalAmt)/100.0)+"元",zbs:totalCount},()=>{
                $('.modal1').show()
            })
        }else{
            alert(JSON.parse(res).msg)
        }
       
      //  that.setState({path:JSON.parse(res).data.oldPath})
       } 
      }, 
      error:function(err){ 
       alert("网络连接失败,稍后重试",err); 
      } 
     }) 
    }


    uploadfile(e){
        $('#pic').click()
        // console.log(e,'uploadfile');
    //     let{chosefile} = this.state,that = this;
    //     if(!chosefile){
    //         alert('请先选择文件')
    //     }else{
       
    //  }
     }



    componentDidMount() {

        // let userdata = JSON.parse($.cookie('userdata')),{merchantName,templateUrl}= userdata
        // console.log(API_HEAD+userdata.templateUrl,'userdata');
        //     this.setState({merchantName,templateUrl:API_HEAD+templateUrl})



        

       // console.log(JSON.parse(userdata),'ppp');
       
        
       //  this.setState({ showloading: 'ON' })
        // let that = this, statehtml = [], typehtml = []
        // statehtml.push(
        //     <option value="ALL">全部</option>
        // )
        // statehtml.push(
        //     <option value="ON">上架</option>
        // )
        // statehtml.push(
        //     <option value="OFF">下架</option>
        // )
        // that.setState({ statehtml })
        // getTypelist(res => {
        //     if (res.issuccess == 1) {
        //         if (res.list.length > 0) {
        //             typehtml.push(
        //                 <option value="0">请选择</option>
        //             )
        //             res.list.forEach((x, i) => {
        //                 typehtml.push(
        //                     <option key={i} value={x.id}>{x.name} </option>
        //                 )

        //             })
        //             this.setState({ typehtml })
        //         }
        //     }
        // })
        $('.modal1').hide()
        // testdingcan(res=>{
        // })
         this.setState({ showloading: '' })
       // this.freshlist()

    }

    add(){
        let {totalAmt,totalCount,oldPath}=this.state,that = this;
        gzaddBatch(totalAmt,totalCount,oldPath,res=>{
            if(res.code=='0'){
              //  alert('新增成功！')
              showAlert($('.alertarea'), '新增成功！', 'alsucc', 'success')
                $('.modal1').hide()
                that.setState({listitem:[]},()=>{
                    this.freshlist()
                }) 
            }

        })

    }
    
    freshlist() {
        
         let { pagesize, start, no } = this.state
         list_getlist(pagesize,start,no,res=>{
             console.log(res,'resres');
            this.setState({ showloading: '' })
             if(res.data.total>0){
                 console.log('aaa');
                 //this.setState({total:res.data.total})
                 if (start == 1) {
                                let pagecount = Math.ceil(res.data.total / pagesize);
                                this.setpager(pagecount, start);
                                this.setState({ start, total: res.data.total })
                            }
                 this.formatlist(res.data.list);
                 $('#btn_download').hover(()=>{
                    console.log(111,'hhhh');
                },()=>{

                })
             }
         })
        // Goodsgetlist({ pagesize, start, keyword, type, state }, res => {
        //     this.setState({ showloading: '' })
        //     if (res.issuccess == 1) {
        //         if (start == 1) {
        //             let pagecount = Math.ceil(res.total / pagesize);
        //             this.setpager(pagecount, start);
        //             this.setState({ start, total: res.total })
        //         }
        //         this.formatlist(res.list);
        //     }
        // })

    }
    setpager(pagecount, start) {
        let counts = [];
        for (let i = 0; i < pagecount; i++) {
            counts.push(start + i)
        }
        this.setState({ counts, pagestart: 0 })
    }
    clickpage(e) {
        let { start } = this.state
        console.log({e,start},'clickpage');

        if(start==e){
            start++;
        }else{
            start = e+1
        }

        this.setState({ pagestart: e, start }, () => {
            this.freshlist()
        })
    }
    setpage(e) {
        let { pagesize, start } = this.state
        pagesize = parseInt(e)
        start = 1
        this.setState({ pagesize, start }, () => {
            this.freshlist()
        })
    }
    inputchange(prop, e) {
        this.setState({ [prop]: e.target.value })
    }
    inputchange1(prop, id, e) {
        let that = this;
        if (prop == "state") {
            that.setState({ showloading: 'ON' })
            Shopsetstate(id, res => {
                if (res.issuccess == 1) {
                    alert("设置成功")
                    that.freshlist()
                } else {
                    that.setState({ showloading: '' })
                    alert(res.msg)
                }
            })
        } else if (prop == "isrecommend") {
            that.setState({ showloading: 'ON' })
            Shopsetrecommend(id, res => {
                if (res.issuccess == 1) {
                    alert("设置成功")
                    that.freshlist()
                } else {
                    that.setState({ showloading: '' })
                    alert(res.msg)
                }
            })
        }

    }
    search() {
        this.setState({listitem:[]},()=>{
            this.freshlist()
        })
    }
    closemodal(){
        $('.modal1').hide()
    }
   
    reset() {
        this.setState({ state: 'ON', no: '' }, () => {
            this.freshlist()
        })
    }
    render() {
        let { listitem, zje,zbs,templateUrl, no,sfzh, jine, result,merchantName } = this.state;

        return (
            <div className="breadLinebox">
                 <div class="alertarea" id='alsucc' >
    </div>
                <div className="modal1" >
                <div onClick={this.closemodal.bind(this)} className="mask"></div>
                <div className="wrap">
                    {/* <div  className="close-div">
                        <img onClick={this.closemodal.bind(this)} src="./src/close1.png" alt="" /> 
                    </div> */}
                    <div className="word">
                        <p className="p1">请核对表格信息</p>
                    </div>
                    <div className="content">
                        <p className="p1">总金额</p>
                        <p className="p2">{zje}</p>
                    </div>
                    <div className="content">
                        <p className="p1">总笔数</p>
                        <p className="p2">{zbs}</p>
                    </div>
            <div className="btns">
            <p className="add" onClick={this.add.bind(this)}>确定</p>
            <p className="add" onClick={this.closemodal.bind(this)}>取消</p>
            </div>
                </div>

                </div>

                <Loading hidden={this.state.showloading != 'ON'} />
                <p className="merchantName">{merchantName}</p>
                <div className='panel-default content_wrap'>
                    <div className="breadLine disflexbetween">
                        <div className="img">
                            {/* <img src='./src/01.gif' /> */}
                            工资管理
                        </div>
                    </div>
                    <div className="disflexbetween">
                        <div className="search ">
                            <div className="left">
                            <antd.Input placeholder="请输入批次号" allowClear value={no} onChange={this.inputchange.bind(this, 'no')} className="input" />
                            <p className="button l" onClick={this.search.bind(this)} >搜索</p>
                            <p className="button" onClick={this.reset.bind(this)} >重置</p>
                            </div>
                            <div className="tabletit">
                                <a href={templateUrl} className="links">模板下载</a>

                                <form id="uploadthis" enctype="multipart/form-data" method="post"> 
 <input type="file"  onChange={this.changefile.bind(this)}  name="upload"  style={{ display: "none" }} id="pic"/> 
 {/* <input type="button" value="提交" onClick={this.uploadfile.bind(this)}/>  */}
 {/* <button type="button" onClick={this.uploadfile.bind(this)} className="submitbutton">上传</button> */}
 <p className="add" onClick={this.uploadfile.bind(this)}><img src="./src/addicon.png"></img>新增代发</p>
</form> 

                            
                        </div>
                        </div>

                      
                    </div>
                    <div className="contentBox">

                        <table className="tab">
                            <thead>
                                <tr>
                                    <th className="tconter">批次号</th>
                                    <th className="tconter">创建时间</th>
                                    <th className="tconter">状态</th>
                                    <th className="tconter">总金额</th>
                                    <th className="tconter">总笔数</th>
                                    <th className="tconter">本地路径</th>
                                    {/* <th>是否新人专享</th>
                                    <th>是否会员专享</th> */}
                                    <th className="cz tconter">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {listitem}
                            </tbody>
                        </table>
                        {this.state.wulist}
                        <div className="pagerbox">
                            <p>共{this.state.total}条</p>
                            <Pager counts={this.state.counts} click={this.clickpage.bind(this)} change={this.setpage.bind(this)} index={this.state.pagestart} />
                        </div>
                    </div>
                    {/* <div class="jsfw">江西川星科技有限公司提供技术支持</div> */}
                </div>
            </div>


        )


    }
}

ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='list' height='list' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)